package com.example.searchcenter.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.searchcenter.R;

import com.example.searchcenter.helper.AlertDialogManager;
import com.example.searchcenter.helper.ConnectionDetector;
import com.example.searchcenter.helper.JSONParser;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("NewApi")
public class ActivitiesFragment extends Fragment {

	ListView list_activity;
	TextView ver;
	TextView name;
	TextView thumbnail;
	View rootView;
	
	// Connection Detector
	ConnectionDetector cd;
	
	// Alert dialog manager
	AlertDialogManager alert = new AlertDialogManager();
	
	// Hashmap articlelist
	ArrayList<HashMap<String, String>> activitylist = new ArrayList<HashMap<String,String>>();
	
	// URL get Json
	private static String url = "http://tinhnguyen.edu.vn/apis/getAllActivities";
	private static final String url_image = "https://tinhnguyen.edu.vn/public/img/activities/thumbs/";
	public static final String TAG_ACTIVITIES = "activities";
	public static final String TAG_ID_ACTIVITY = "cid";
	public static final String TAG_CREATEDATE = "createDate";
	public static final String TAG_NAME = "name";
	public static final String TAG_DESCRIPTION = "description";
	public static final String TAG_STARTDAY = "startday";
	public static final String TAG_ENDDAY = "endday";
	public static final String TAG_LOCATION = "vplaceName";
	public static final String TAG_THUMBNAILIMAGEURL = "thumbnailImageUrl";
	public static final String TAG_COUNT_ACTIVITIES = "count_activities";

	JSONArray arrActivity = null;
	ActivitiesAdapter activityadapter;
	
	public ActivitiesFragment(){}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState){
		rootView = inflater.inflate(R.layout.fragment_activities_home, container,false);
		
		new ListActivities().execute();
        return rootView;
	}
	
	// Count Activity
	public static String getCounterActivities()
	{
		JSONParser jParser = new JSONParser();
		// Getting JSON from URL
		JSONObject json = jParser.getJSONFromUrl(url);
		String counter = null;
		try{
			counter = json.getString(TAG_COUNT_ACTIVITIES);
		}
		catch(JSONException e){
			e.printStackTrace();
		}
		return counter;
	}
	
	private class ListActivities extends AsyncTask<String, String, JSONObject>{
		private ProgressDialog pDialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Getting Data ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		@Override
		protected JSONObject doInBackground(String... args) {
			JSONParser jParser = new JSONParser();
			// Getting JSON from URL
			JSONObject json = jParser.getJSONFromUrl(url);
			//Toast.makeText(getApplicationContext(),json.toString(), Toast.LENGTH_LONG).show();
			return json;
		}
		
		@Override
		protected void onPostExecute(JSONObject json){
			pDialog.dismiss();
			try{
				arrActivity = json.getJSONArray(TAG_ACTIVITIES);
				
				for(int i = 0; i < arrActivity.length(); i++)
				{
					JSONObject c = arrActivity.getJSONObject(i);
					String cid = c.getString(TAG_ID_ACTIVITY);
					String createDate = c.getString(TAG_CREATEDATE);
					String name = c.getString(TAG_NAME);
					String description = c.getString(TAG_DESCRIPTION);
					String location = c.getString(TAG_LOCATION);
					String thumbnail = url_image+c.getString(TAG_THUMBNAILIMAGEURL);
					
					// Adding value HashMap key => value
					HashMap<String, String> hash_activity = new HashMap<String, String>();
					hash_activity.put(TAG_ID_ACTIVITY, cid);
					hash_activity.put(TAG_CREATEDATE, createDate);
					hash_activity.put(TAG_NAME, name);
					hash_activity.put(TAG_DESCRIPTION, description);
					hash_activity.put(TAG_LOCATION, location);
					hash_activity.put(TAG_THUMBNAILIMAGEURL, thumbnail);
					
					activitylist.add(hash_activity);
					
					list_activity = (ListView) rootView.findViewById(R.id.list_activity);
					activityadapter = new ActivitiesAdapter(getActivity(), activitylist);
					
					list_activity.setAdapter(activityadapter);
					
					// Click go to detail activity
					list_activity.setOnItemClickListener(new AdapterView.OnItemClickListener(){
						
						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							// getting values from selected ListItem
							String id_activity = ((TextView) view
									.findViewById(R.id.id_activity))
									.getText().toString();
							
							// Starting new intent
							Intent in = new Intent(getActivity(),DetailActivity.class);
							// sending pid to next activity
							in.putExtra(TAG_ID_ACTIVITY,id_activity);
							// starting new activity and expecting some response
							// back
							startActivityForResult(in, 100);
							
						}
					});
				}
			}
			catch(JSONException e){
				e.printStackTrace();
			}
		}
	}
}
